package com.itoffer.web;


import com.itoffer.pojo.Applicant;
import com.itoffer.service.ApplicantService;
import com.itoffer.service.impl.ApplicantServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
   private ApplicantService applicantService = new ApplicantServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名和密码
        String applicant_email = req.getParameter("applicant_email");
        String applicant_pwd = req.getParameter("applicant_pwd");

        //解决乱码问题
        byte[] bytes = applicant_email.getBytes(StandardCharsets.ISO_8859_1);
        applicant_email = new String(bytes, StandardCharsets.UTF_8);

//        System.out.println(applicant_email);
//        System.out.println(applicant_pwd);



        //获取复选框数据
        String remember = req.getParameter("remember");
//        System.out.println(remember);

        //System.out.println(remember);

        //调用Service层方法
        Applicant applicant = applicantService.Login(applicant_email, applicant_pwd);

        if(applicant!=null){
            //登录成功
            //创建cookie对象
            Cookie c_applicant_email = new Cookie("applicant_email", applicant_email);
            Cookie c_applicant_pwd = new Cookie("applicant_pwd", applicant_pwd);
            //判断是否勾选复选框
            if("1".equals(remember)){
                //如果被勾选，发送cookie
                //设置cookie存活时间
                c_applicant_email.setMaxAge(60*60*24*7);
                c_applicant_pwd.setMaxAge(60*60*24*7);

                //2.发送cookie
                resp.addCookie(c_applicant_email);
                resp.addCookie(c_applicant_pwd);
            }else{
                c_applicant_email.setMaxAge(0);
                c_applicant_pwd.setMaxAge(0);
            }
            //将登录成功的applicant对象，存储到session中
            HttpSession session = req.getSession();
            session.setAttribute("applicant",applicant);



            //跳转到成功页面去,这里由于用了ajax无法直接，给前端一个跳转的url
            resp.setContentType("text/json;charset = utf-8");
            resp.getWriter().write("http://localhost:8080/itoffer/loginSuccess.jsp");

        }else{
            //登录失败
            resp.setContentType("text/json;charset = utf-8");
            resp.getWriter().write("false");
            //req.getRequestDispatcher("/error.html").forward(req,resp);
            //
            //resp.getWriter().write("");
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
